import { setSwitch} from '../../api/index.js'
import { navigateBackMiniProgram } from '../../utils/util.js'

// pages/changeId/changeId.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [
      {
        id: 0,
        name: '店主',
        identity: 'SHOP'
      },
      {
        id: 1,
        name: '区域服务商',
        identity: 'REGION'
      },
      {
        id: 2,
        name: '运营服务商',
        identity: 'OPERATION'
      },
      {
        id: 3,
        name: '电子票箱购买人',
        identity: 'BUYER'
      },
    ],
    curIndex: 0,
    identity: ''
  },

  onTap: function(e) {
    const {currentTarget: {dataset:{index,identity}}} = e

    this.setData({
      curIndex: index,
      identity
    },() => {
      this.switchIdentity()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  onShow: function() {
    this.initSetIdentity() 
  },

  switchIdentity: function() {
    const { identity} = this.data
    wx.setStorageSync('identity', identity)

    setSwitch({identity})
    .then(res => {
      if(identity === 'SHOP') {
        return navigateBackMiniProgram()
      }

      wx.navigateTo({
        url: '/pages/home/home',
      })
    })
    .catch(e => {
      console.log(e, '切换身份')
      if(e.statusCode === 401) {
        return wx.navigateTo({
          url: '/pages/region/region'
        })
      }
    })
  },

  initSetIdentity: function() {
    const {list} = this.data
    const identity = wx.getStorageSync('identity')
    const curIndex = list.find(l => l.identity === identity).id

    this.setData({
      identity,
      curIndex
    })
  }
  
})